package com.example.blog.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.example.blog.entity.Blog;
import com.example.blog.entity.BlogType;
import com.example.blog.service.BlogService;
import com.example.blog.service.BlogTypeService;

/**
 * 博客控制器
 */
@RestController
@RequestMapping("/api/blog")
@CrossOrigin
public class BlogController {

    @Autowired
    private BlogService blogService;
    
    @Autowired
    private BlogTypeService blogTypeService;
    
    /**
     * 创建博客
     */
    @PostMapping("/create")
    public Map<String, Object> createBlog(
            @RequestParam String title,
            @RequestParam String content,
            @RequestParam Integer typeId,
            @RequestParam Integer userId,
            @RequestParam(required = false) String summary,
            @RequestParam(required = false) MultipartFile coverImage,
            @RequestParam(defaultValue = "false") Boolean isPublished
    ) {
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setTypeId(typeId);
        blog.setUserId(userId);
        blog.setSummary(summary);
        blog.setIsPublished(isPublished);
        
        return blogService.createBlog(blog);
    }
    
    /**
     * 更新博客
     */
    @PutMapping("/update")
    public Map<String, Object> updateBlog(@RequestBody Blog blog) {
        return blogService.updateBlog(blog);
    }
    
    /**
     * 发布/取消发布博客
     */
    @PutMapping("/publish/{blogId}")
    public Map<String, Object> updatePublishStatus(@PathVariable Integer blogId, @RequestParam Boolean isPublished) {
        Map<String, Object> map = new HashMap<>();
        boolean result = blogService.updatePublishStatus(blogId, isPublished);
        if (result) {
            map.put("success", true);
            map.put("message", isPublished ? "发布成功" : "取消发布成功");
        } else {
            map.put("success", false);
            map.put("message", isPublished ? "发布失败" : "取消发布失败");
        }
        return map;
    }
    
    /**
     * 删除博客
     */
    @DeleteMapping("/{blogId}")
    public Map<String, Object> deleteBlog(@PathVariable Integer blogId) {
        Map<String, Object> map = new HashMap<>();
        boolean result = blogService.deleteBlog(blogId);
        if (result) {
            map.put("success", true);
            map.put("message", "删除成功");
        } else {
            map.put("success", false);
            map.put("message", "删除失败");
        }
        return map;
    }
    
    /**
     * 获取博客详情
     */
    @GetMapping("/{blogId}")
    public Map<String, Object> getBlogById(@PathVariable Integer blogId) {
        Map<String, Object> map = new HashMap<>();
        Blog blog = blogService.getBlogById(blogId);
        
        if (blog != null) {
            // 增加浏览量
            blogService.incrementViews(blogId);
            
            map.put("success", true);
            map.put("blog", blog);
        } else {
            map.put("success", false);
            map.put("message", "博客不存在");
        }
        return map;
    }
    
    /**
     * 获取所有博客（分页）
     */
    @GetMapping("/list")
    public Map<String, Object> getAllBlogs(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String query,
            @RequestParam(required = false) Integer typeId) {
        return blogService.getAllBlogs(pageNum, pageSize, query, typeId);
    }
    
    /**
     * 获取所有已发布博客（分页）
     */
    @GetMapping("/published")
    public Map<String, Object> getAllPublishedBlogs(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String query,
            @RequestParam(required = false) Integer typeId) {
        return blogService.getAllPublishedBlogs(pageNum, pageSize, query, typeId);
    }
    
    /**
     * 获取用户的博客
     */
    @GetMapping("/user/{userId}")
    public List<Blog> getBlogsByUserId(@PathVariable Integer userId) {
        return blogService.getBlogsByUserId(userId);
    }
    
    /**
     * 获取用户的已发布博客
     */
    @GetMapping("/user/{userId}/published")
    public List<Blog> getPublishedBlogsByUserId(@PathVariable Integer userId) {
        return blogService.getPublishedBlogsByUserId(userId);
    }
    
    /**
     * 获取分类下的博客
     */
    @GetMapping("/type/{typeId}")
    public List<Blog> getBlogsByTypeId(@PathVariable Integer typeId) {
        return blogService.getBlogsByTypeId(typeId);
    }
    
    /**
     * 获取热门博客
     */
    @GetMapping("/hot")
    public List<Blog> getHotBlogs(@RequestParam(defaultValue = "10") Integer limit) {
        return blogService.getHotBlogs(limit);
    }
    
    /**
     * 搜索博客
     */
    @GetMapping("/search")
    public List<Blog> searchBlogs(@RequestParam String keyword) {
        return blogService.searchBlogs(keyword);
    }
    
    /**
     * 用户点赞博客
     */
    @PostMapping("/like")
    public Map<String, Object> likeBlog(@RequestParam Integer userId, @RequestParam Integer blogId) {
        return blogService.likeBlog(userId, blogId);
    }
    
    /**
     * 用户取消点赞博客
     */
    @PostMapping("/unlike")
    public Map<String, Object> unlikeBlog(@RequestParam Integer userId, @RequestParam Integer blogId) {
        return blogService.unlikeBlog(userId, blogId);
    }
    
    /**
     * 检查用户是否点赞了博客
     */
    @GetMapping("/check-like")
    public Map<String, Object> checkLike(@RequestParam Integer userId, @RequestParam Integer blogId) {
        Map<String, Object> map = new HashMap<>();
        boolean isLiked = blogService.isLikedByUser(userId, blogId);
        map.put("isLiked", isLiked);
        return map;
    }
    
    /**
     * 获取用户点赞的所有博客ID
     */
    @GetMapping("/user/{userId}/likes")
    public List<Integer> getLikedBlogIds(@PathVariable Integer userId) {
        return blogService.getLikedBlogIdsByUserId(userId);
    }
    
    /**
     * 创建博客分类
     */
    @PostMapping("/type/create")
    public Map<String, Object> createBlogType(@RequestBody BlogType blogType) {
        return blogTypeService.createBlogType(blogType);
    }
    
    /**
     * 更新博客分类
     */
    @PutMapping("/type/update")
    public Map<String, Object> updateBlogType(@RequestBody BlogType blogType) {
        return blogTypeService.updateBlogType(blogType);
    }
    
    /**
     * 删除博客分类
     */
    @DeleteMapping("/type/{typeId}")
    public Map<String, Object> deleteBlogType(@PathVariable Integer typeId) {
        Map<String, Object> map = new HashMap<>();
        boolean result = blogTypeService.deleteBlogType(typeId);
        if (result) {
            map.put("success", true);
            map.put("message", "删除成功");
        } else {
            map.put("success", false);
            map.put("message", "删除失败");
        }
        return map;
    }
    
    /**
     * 获取博客分类详情
     */
    @GetMapping("/type/info/{typeId}")
    public Map<String, Object> getBlogTypeById(@PathVariable Integer typeId) {
        Map<String, Object> map = new HashMap<>();
        BlogType blogType = blogTypeService.getBlogTypeById(typeId);
        if (blogType != null) {
            map.put("success", true);
            map.put("blogType", blogType);
        } else {
            map.put("success", false);
            map.put("message", "分类不存在");
        }
        return map;
    }
    
    /**
     * 获取用户的所有博客分类
     */
    @GetMapping("/type/user/{userId}")
    public List<BlogType> getBlogTypesByUserId(@PathVariable Integer userId) {
        return blogTypeService.getBlogTypesByUserId(userId);
    }
    
    /**
     * 获取所有博客类型
     */
    @GetMapping("/types")
    public List<BlogType> getAllBlogTypes() {
        return blogTypeService.getAllBlogTypes();
    }
    
    /**
     * 获取热门博客
     * @param sortType 排序类型：latest-最新，views-最多浏览，likes-最多点赞
     * @return 博客列表
     */
    @GetMapping("/top")
    public ResponseEntity<List<Blog>> getTopBlogs(@RequestParam(required = false, defaultValue = "latest") String sortType) {
        List<Blog> blogs = blogService.getTopBlogs(sortType);
        return ResponseEntity.ok(blogs);
    }
    
    /**
     * 用户点赞博客（简化版，不需要用户ID）
     */
    @PostMapping("/{blogId}/like")
    public Map<String, Object> simpleLikeBlog(@PathVariable Integer blogId) {
        Map<String, Object> map = new HashMap<>();
        try {
            // 简化实现，只增加点赞数
            blogService.incrementLikes(blogId);
            map.put("success", true);
            map.put("message", "点赞成功");
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", "点赞失败: " + e.getMessage());
        }
        return map;
    }
} 